package com.gengzp.rpc.strategy.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gengzp.rpc.enums.RpcServiceRegisterIpTypeEnum;
import com.gengzp.rpc.model.nacos.dto.NacosServiceInstanceV1Dto;
import com.gengzp.rpc.model.nacos.req.SearchNacosServiceInstanceListV1Req;
import com.gengzp.rpc.model.nacos.resp.SearchNacosServiceInstanceListV1Resp;
import com.gengzp.rpc.model.serviceRegistration.resp.SearchServiceRegistrationResp;
import com.gengzp.rpc.strategy.RpcRemoteServiceRouteStrategy;
import com.gengzp.rpc.tools.RpcEnvironmentVariableReader;
import com.gengzp.rpc.tools.RpcHttpRequester;
import com.gengzp.rpc.tools.RpcJsonConvertor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.gengzp.rpc.constants.RpcEnvironmentKeyConstants.*;
import static com.gengzp.rpc.constants.RpcHttpRequestUrlConstants.HTTP_REQUEST_URL_PREFIX;
import static com.gengzp.rpc.constants.RpcHttpRequestUrlConstants.NACOS_V1_SERVICE_INSTANCE_LIST;

/**
 * @ClassName RpcRemoteServiceRouteNacosV1StrategyImpl
 * @Description nacos_v1 服务路由策略
 * @Author gengzp
 * @Date 2025/8/20 17:14
 */
@Component
public class RpcRemoteServiceRouteNacosV1StrategyImpl implements RpcRemoteServiceRouteStrategy {

    @Override
    public List<String> getServiceInstanceAddressByServiceName(String serviceName) {
        SearchNacosServiceInstanceListV1Resp resp = getNacosServiceInstanceListV1Resp(serviceName);
        if (resp == null || resp.getHosts() == null || resp.getHosts().isEmpty()) {
            return Collections.emptyList();
        }

        // 将ip地址和端口号拼接起来
        return resp.getHosts().stream().map(v ->
                HTTP_REQUEST_URL_PREFIX + v.getIp() + ":" + v.getPort()).collect(Collectors.toList());
    }

    @Override
    public List<SearchServiceRegistrationResp> getServiceRegistrationInformationByServiceName(String serviceName) {
        SearchNacosServiceInstanceListV1Resp resp = getNacosServiceInstanceListV1Resp(serviceName);
        if (resp == null || resp.getHosts() == null || resp.getHosts().isEmpty()) {
            return Collections.emptyList();
        }

        List<SearchServiceRegistrationResp> result = new ArrayList<>();
        if (resp.getHosts() == null || resp.getHosts().isEmpty()) {
            return Collections.emptyList();
        }

        for (NacosServiceInstanceV1Dto host : resp.getHosts()) {
            SearchServiceRegistrationResp serviceRegistrationResp = new SearchServiceRegistrationResp();
            serviceRegistrationResp.setServiceName(host.getServiceName());
            serviceRegistrationResp.setAddress(host.getIp() + ":" + host.getPort());
            // nacos默认使用内网注册
            serviceRegistrationResp.setRegisterIpType(RpcServiceRegisterIpTypeEnum.INNER.getName());
            result.add(serviceRegistrationResp);
        }

        return result;
    }

    /**
     * 查询服务注册信息
     *
     * @param serviceName 服务名
     * @return 服务注册信息
     */
    private SearchNacosServiceInstanceListV1Resp getNacosServiceInstanceListV1Resp(String serviceName) {
        // 1.组装查询条件
        SearchNacosServiceInstanceListV1Req req = new SearchNacosServiceInstanceListV1Req();
        req.setServiceName(serviceName);
        req.setGroupName(RpcEnvironmentVariableReader.getEnvironmentVariable(RPC_NACOS_GROUP_NAME));
        req.setNamespaceId(RpcEnvironmentVariableReader.getEnvironmentVariable(RPC_NACOS_NAMESPACE_ID));
        req.setHealthyOnly(true);

        // 2.调用nacos接口, 获取服务实例集合
        return RpcHttpRequester.get(
                HTTP_REQUEST_URL_PREFIX + RpcEnvironmentVariableReader
                        .getEnvironmentVariable(RPC_NACOS_CONNECT_ADDRESS) + NACOS_V1_SERVICE_INSTANCE_LIST,
                RpcJsonConvertor.convertObjectToMap(req),
                null,
                new TypeReference<>() {
                });
    }

}
